package com.jijuxie.agent.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jijuxie.agent.domain.Agent;
import com.jijuxie.agent.domain.Customer;
import com.jijuxie.agent.domain.DealRecord;
import com.jijuxie.agent.domain.vo.AgentStatsVO;
import com.jijuxie.agent.mapper.AgentMapper;
import com.jijuxie.agent.mapper.CustomerMapper;
import com.jijuxie.agent.mapper.DealRecordMapper;
import com.jijuxie.agent.service.IAgentService;
import com.jijuxie.common.exception.ServiceException;
import com.jijuxie.common.core.R;
import org.apache.commons.lang3.StringUtils;

import cn.dev33.satoken.stp.StpUtil;

import java.time.LocalDateTime;

/**
 * 经纪人服务实现类 处理经纪人相关的业务逻辑
 *
 * @author jijuxie
 */
@Service
public class AgentServiceImpl extends ServiceImpl<AgentMapper, Agent> implements IAgentService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private DealRecordMapper dealRecordMapper;

    /**
     * 经纪人认证 包含资料验证、状态设置等
     *
     * @param agent 经纪人信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certify(Agent agent) {
        // 检查是否已提交申请
        Agent existAgent = baseMapper.selectAgentByUserId(StpUtil.getLoginIdAsLong());
        if (existAgent != null) {
            // 如果申请状态是待审核或已通过，不允许再次申请
            if ("0".equals(existAgent.getStatus())) {
                throw new ServiceException("您已提交申请，正在审核中");
            } else if ("1".equals(existAgent.getStatus())) {
                throw new ServiceException("您的经纪人申请已通过，不能重复申请");
            } else if ("2".equals(existAgent.getStatus())) {
                // 如果是被拒绝状态，允许重新申请
                // 更新原有申请记录，而不是创建新记录
                agent.setAgentId(existAgent.getAgentId());
                agent.setUserId(StpUtil.getLoginIdAsLong());
                agent.setStatus("0"); // 设置为待审核状态
                agent.setDelFlag("0");
                agent.setCreateTime(LocalDateTime.now()); // 更新申请时间
                agent.setAuditTime(null); // 清除之前的审核时间
                agent.setAuditorId(null); // 清除之前的审核人
                agent.setAuditRemark(null); // 清除之前的审核备注
                updateById(agent);
                return;
            }
        }

        // 首次申请，设置默认值
        agent.setUserId(StpUtil.getLoginIdAsLong());
        agent.setStatus("0"); // 待审核
        agent.setDelFlag("0");
        // 设置申请时间
        agent.setCreateTime(LocalDateTime.now());
        save(agent);
    }

    /**
     * 审核认证 更新认证状态,发送通知
     *
     * @param agentId 经纪人ID
     * @param status 审核状态
     * @param remark 审核备注
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long agentId, String status, String remark) {
        Agent agent = getById(agentId);
        if (agent == null) {
            throw new ServiceException("经纪人不存在");
        }
        agent.setStatus(status);
        agent.setRemark(remark);
        updateById(agent);
    }

    /**
     * 获取经纪人业绩统计 统计成交数据、客户数据等
     *
     * @param agentId 经纪人ID
     * @return 业绩统计数据
     */
    @Override
    public AgentStatsVO getAgentStats(Long agentId) {
        AgentStatsVO stats = new AgentStatsVO();

        // 获取总体业绩
        Map<String, Object> totalStats = dealRecordMapper.selectAgentStats(agentId);
        stats.setTotalDealCount(Integer.valueOf(totalStats.get("totalDealCount").toString()));
        stats.setTotalDealAmount(new BigDecimal(totalStats.get("totalDealAmount").toString()));

        // 获取本月业绩
        Map<String, Object> monthStats = dealRecordMapper.selectMonthStats(agentId);
        stats.setMonthDealCount(Integer.valueOf(monthStats.get("monthDealCount").toString()));
        stats.setMonthDealAmount(new BigDecimal(monthStats.get("monthDealAmount").toString()));

        return stats;
    }

    /**
     * 添加客户 新增客户信息,设置默认状态
     *
     * @param customer 客户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCustomer(Customer customer) {
        customer.setAgentId(StpUtil.getLoginIdAsLong());
        customer.setDelFlag("0");
        customerMapper.insert(customer);
    }

    /**
     * 添加成交记录 记录成交信息,计算佣金等
     *
     * @param record 成交记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDealRecord(DealRecord record) {
        record.setAgentId(StpUtil.getLoginIdAsLong());
        record.setDelFlag("0");
        // 计算佣金金额
        record.setCommissionAmount(record.getDealPrice()
                .multiply(record.getCommissionRate())
                .divide(new BigDecimal("100")));
        dealRecordMapper.insert(record);
    }

    @Override
    public Agent getAgentInfo(Long agentId) {
        System.out.println("获取经纪人详情: agentId=" + agentId);
        Agent agent = getById(agentId);
        if (agent == null || "1".equals(agent.getDelFlag())) {
            System.out.println("经纪人不存在或已删除: agentId=" + agentId);
            throw new ServiceException("经纪人不存在");
        }
        
        // 输出经纪人信息日志，帮助调试
        System.out.println("经纪人详情: " + 
                           "姓名=" + agent.getRealName() +
                           ", 头像=" + agent.getAvatar() +
                           ", 职位=" + agent.getPosition() +
                           ", 成交量=" + agent.getDeals() +
                           ", 评分=" + agent.getRating() +
                           ", 从业年限=" + agent.getWorkYears() +
                           ", 专业领域=" + agent.getExpertise());
        
        // 确保关键字段不为null
        if (agent.getRating() == null) {
            agent.setRating(new BigDecimal("0.0"));
            System.out.println("修正经纪人评分为默认值0.0");
        }
        
        if (agent.getDeals() == null) {
            agent.setDeals(0);
            System.out.println("修正经纪人成交量为默认值0");
        }
        
        if (agent.getExpertise() == null) {
            agent.setExpertise("");
            System.out.println("修正经纪人专业领域为空字符串");
        }
        
        return agent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAgent(Agent agent) {
        // 不允许修改用户ID和认证状态
        agent.setUserId(null);
        agent.setStatus(null);
        updateById(agent);
    }

    @Override
    public Agent getMyAgentInfo() {
        return baseMapper.selectAgentByUserId(StpUtil.getLoginIdAsLong());
    }

    @Override
    public Page<Agent> selectAgentPage(Page<Agent> page, Agent agent) {
        LambdaQueryWrapper<Agent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(agent.getRealName() != null, Agent::getRealName, agent.getRealName())
                .like(agent.getCompany() != null, Agent::getCompany, agent.getCompany())
                .eq(agent.getStatus() != null, Agent::getStatus, agent.getStatus())
                .orderByDesc(Agent::getCreateTime);
        
        // 使用自定义查询方法，避免查询不存在的字段
        return baseMapper.selectAgentPageCustom(page, queryWrapper);
    }

    @Override
    public AgentStatsVO getMyStats() {
        return getAgentStats(StpUtil.getLoginIdAsLong());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomer(Customer customer) {
        customerMapper.updateById(customer);
    }

    @Override
    public Page<Customer> selectCustomerPage(Page<Customer> page, Customer customer) {
        return customerMapper.selectPage(page, new LambdaQueryWrapper<Customer>()
                .eq(Customer::getAgentId, StpUtil.getLoginIdAsLong())
                .like(customer.getName() != null, Customer::getName, customer.getName())
                .eq(customer.getDelFlag() != null, Customer::getDelFlag, customer.getDelFlag())
                .orderByDesc(Customer::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmDeal(Long recordId) {
        DealRecord record = dealRecordMapper.selectById(recordId);
        if (record == null) {
            throw new ServiceException("成交记录不存在");
        }
        record.setStatus("1");
        dealRecordMapper.updateById(record);

        // 更新客户状态
        Customer customer = customerMapper.selectById(record.getCustomerId());
        if (customer != null) {
            customer.setStatus("2");
            customerMapper.updateById(customer);
        }
    }

    @Override
    public Page<DealRecord> selectDealRecordPage(Page<DealRecord> page, DealRecord record) {
        return dealRecordMapper.selectPage(page, new LambdaQueryWrapper<DealRecord>()
                .eq(DealRecord::getAgentId, StpUtil.getLoginIdAsLong())
                .eq(DealRecord::getDelFlag, "0")
                .orderByDesc(DealRecord::getCreateTime));
    }

    @Override
    public R<Object> getAgentList(String keyword, Integer pageNum, Integer pageSize) {
        try {
            LambdaQueryWrapper<Agent> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(StringUtils.isNotBlank(keyword), Agent::getRealName, keyword)
                    .or()
                    .like(StringUtils.isNotBlank(keyword), Agent::getAgentNo, keyword)
                    .eq(Agent::getDelFlag, "0")
                    .eq(Agent::getStatus, "1"); // 只查询已认证的经纪人
            
            Page<Agent> page = new Page<>(pageNum, pageSize);
            page = baseMapper.selectAgentPageCustom(page, wrapper);
            
            // 处理可能的空结果
            if (page == null || page.getRecords() == null) {
                Page<Agent> emptyPage = new Page<>(pageNum, pageSize, 0);
                emptyPage.setRecords(new ArrayList<>());
                page = emptyPage;
            }
            
            // 转换为前端需要的VO对象，增加空值检查
            Page<com.jijuxie.agent.domain.vo.AgentVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
            List<com.jijuxie.agent.domain.vo.AgentVO> voRecords = page.getRecords().stream().map(agent -> {
                com.jijuxie.agent.domain.vo.AgentVO vo = new com.jijuxie.agent.domain.vo.AgentVO();
                vo.setAgentId(agent.getAgentId());
                vo.setRealName(agent.getRealName() != null ? agent.getRealName() : "未知");
                vo.setAvatar(agent.getAvatar() != null ? agent.getAvatar() : "");
                vo.setPosition(agent.getPosition() != null ? agent.getPosition() : "房产顾问");
                vo.setDealCount(agent.getDeals() != null ? agent.getDeals() : 0);
                
                // 评分处理，确保不会出现空指针异常
                if (agent.getRating() != null) {
                    vo.setRating(agent.getRating());
                    // 将评分（0-5）转换为百分比（0-100）
                    vo.setRatingPercent(agent.getRating().multiply(new BigDecimal("20")).intValue());
                } else {
                    vo.setRating(new BigDecimal("0"));
                    vo.setRatingPercent(0);
                }
                
                vo.setExperienceYears(agent.getWorkYears() != null ? agent.getWorkYears() : 0);
                vo.setCompany(agent.getCompany() != null ? agent.getCompany() : "");
                
                // 从专业领域字段生成标签，确保不为null
                vo.setTags(agent.getExpertise() != null ? agent.getExpertise() : "");
                
                return vo;
            }).collect(Collectors.toList());
            
            voPage.setRecords(voRecords);
            
            System.out.println("经纪人列表获取成功: 总数=" + voPage.getTotal() + ", 记录数=" + voRecords.size());
            return R.ok(voPage);
        } catch (Exception e) {
            e.printStackTrace();
            // 返回空页数据而不是null，确保前端可以正常解析
            Page<com.jijuxie.agent.domain.vo.AgentVO> emptyPage = new Page<>(pageNum, pageSize, 0);
            emptyPage.setRecords(new ArrayList<>());
            return R.ok(emptyPage);
        }
    }

    @Override
    public R<Object> applyAgent(Agent agentInfo) {
        try {
            // 检查是否已提交申请
            Agent existAgent = baseMapper.selectAgentByUserId(StpUtil.getLoginIdAsLong());
            if (existAgent != null) {
                // 如果申请状态是待审核或已通过，不允许再次申请
                if ("0".equals(existAgent.getStatus())) {
                    return R.fail("您已提交申请，正在审核中");
                } else if ("1".equals(existAgent.getStatus())) {
                    return R.fail("您的经纪人申请已通过，不能重复申请");
                } else if ("2".equals(existAgent.getStatus())) {
                    // 如果是被拒绝状态，允许重新申请
                    // 更新原有申请记录，而不是创建新记录
                    agentInfo.setAgentId(existAgent.getAgentId());
                    agentInfo.setUserId(StpUtil.getLoginIdAsLong());
                    agentInfo.setStatus("0"); // 设置为待审核状态
                    agentInfo.setDelFlag("0");
                    agentInfo.setCreateTime(LocalDateTime.now()); // 更新申请时间
                    agentInfo.setAuditTime(null); // 清除之前的审核时间
                    agentInfo.setAuditorId(null); // 清除之前的审核人
                    agentInfo.setAuditRemark(null); // 清除之前的审核备注
                    updateById(agentInfo);
                    return R.ok("重新申请成功，等待审核");
                }
            }

            // 首次申请，设置默认值
            agentInfo.setUserId(StpUtil.getLoginIdAsLong());
            agentInfo.setStatus("0");
            agentInfo.setDelFlag("0");
            agentInfo.setCreateTime(LocalDateTime.now());
            save(agentInfo);
            return R.ok("申请成功，等待审核");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("申请失败: " + e.getMessage());
        }
    }

    @Override
    public R<Object> updateAgentInfo(Agent agentInfo) {
        // 检查经纪人是否存在
        Agent existingAgent = getById(agentInfo.getAgentId());
        if (existingAgent == null || "1".equals(existingAgent.getDelFlag())) {
            return R.fail("经纪人不存在");
        }
        // 更新经纪人信息
        updateById(agentInfo);
        return R.ok();
    }
}
